﻿Create proc sp_phatsinhmaCT 
@TienTo char(5)
as
Declare @Dem as int
Declare @GT as int
Declare @GT1 as int
Declare @GTupdate as char(3)
Declare @Ma as char(11)
select @Dem=count(*) from DM_ChungTu_H where left(MaCT,5) = @TienTo
if(@Dem=0)
	begin
	update DM_TienTo set GiaTri='001' where TienTo=@TienTo
	set @Ma=(@TienTo + '001/' + cast(month(Getdate())as char))
	select @Ma
	end
else
	begin
	select @GT=cast(GiaTri as int) from DM_TienTo where TienTo=@TienTo
	select @GT1=cast(substring(MaCT,6,3) as int) from DM_ChungTu_H where left(MaCT,5) = @TienTo
	if(@GT=@GT1)
	set @GT =cast(@GT+1 as int)
	while len(@GT) <3
		set @GTupdate='0' + @GTupdate
		set @Ma=@TienTo + @GTupdate + '/' + cast(month(getdate()) as char)
	update DM_TienTo set GiaTri=@GTupdate where TienTo=@TienTo
	select @Ma
	end